// 计数排序采用额外辅助空间，排序的时间复杂度O(n)
// 适用于需要较小额外空间的排序
#include <iostream>
using namespace std;

const int maxValue = 99;

void CountSort(int data[], int length)
{
    int * countData = new int[maxValue + 1];
    
    for (int value = 0; value <= maxValue; ++value)
        countData[value] = 0;
    // 统计每个数字出现的次数
    for (int len = 0; len < length; ++len)
    {
        ++countData[data[len]];
    }
    
    int len = 0;
    for(int value = 0; value <= maxValue; ++ value)
    {
        int valueCount = countData[value];

        for(int count = 0; count < valueCount; ++ count)
        {
            data[len] = value;
            ++ len;
        }    
    }
}

int main(int argc, char * argv[])
{
    int data[10000] = {};
    for (int i = 0; i < 10000; ++ i)
    {
        data[i] = i * 20 % maxValue;
    }
    for(int i = 0; i < 10000; ++ i)
    {
        if (i % 20 == 0)
            cout << endl;
        cout << data[i] << " ";
    }
    cout << endl;

    CountSort(data, 10000);
    for(int i = 0; i < 10000; ++ i)
    {
        if (i % 20 == 0)
            cout << endl;
        cout << data[i] << " ";
    }
    cout << endl;
    return 0;
}
